import 'package:flutter/material.dart';
import 'package:sqlite3/sqlite3.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter SQLite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});

  void _insertData() {
    // 打开内存数据库（可以替换为文件数据库）
    final db = sqlite3.openInMemory();

    // 创建表
    db.execute('''
      CREATE TABLE users (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL
      );
    ''');

    // 插入数据
    db.execute('INSERT INTO users (name) VALUES ("Alice")');
    db.execute('INSERT INTO users (name) VALUES ("Bob")');

    // 查询数据（可选，仅用于验证插入是否成功）
    final result = db.select('SELECT * FROM users');
    for (final row in result) {
      print('User: id=${row['id']}, name=${row['name']}');
    }

    // 关闭数据库
    db.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home Screen'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _insertData, // 点击按钮时插入数据
              child: const Text('Insert Data into SQLite'),
            ),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                // 导航到第二个页面
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => const SecondScreen(),
                  ),
                );
              },
              child: const Text('Go to Second Screen'),
            ),
          ],
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  const SecondScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Screen'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // 返回上一个页面
            Navigator.pop(context);
          },
          child: const Text('Go Back to Home Screen'),
        ),
      ),
    );
  }
}